package db

import (
	"fmt"
	"github.com/google/uuid"
	"github.com/jinzhu/gorm"
	"sola/common"
	"sola/utils"
	"time"
)

/*

271972965061492859
admin admin admin

*/

type User struct {
	common.BaseModel
	UserId   string `json:"user_id" gorm:"size:36;NOT NULL"`
	Username string `json:"username" gorm:"size:64;unique_index;NOT NULL"`
	Nickname string `json:"nickname" gorm:"size:64;NOT NULL"`
	Password string `json:"password" gorm:"size:64"`
	ImageUri string `json:"image_uri" gorm:"size:256"`
}

func (user *User) BeforeCreate(scope *gorm.Scope) error {
	return scope.SetColumn("user_id", uuid.New().String())
}

func (user *User) BeforeSave(scope *gorm.Scope) error {
	return scope.SetColumn("updated_at", time.Now())
}

func RegistUser(user *User) (err error) {
	var alreadyUser User
	db.Where(&User{Username: user.Username}).First(&alreadyUser)
	if alreadyUser.Id > 0 {
		err = ErrUserExists
		return
	}
	passwd := user.Password + PasswordSalt
	user.Password = utils.Md5([]byte(passwd))
	db.Create(&user)
	return
}

func Login(user *User) (err error) {
	fmt.Println("Login User:", user)
	originPassword := user.Password
	db.Where(&User{Username: user.Username}).First(&user)
	if user.Id <= 0 {
		err = ErrUserNotExists
		return
	}

	passwd := originPassword + PasswordSalt
	originPasswordSalt := utils.Md5([]byte(passwd))

	if originPasswordSalt != user.Password {
		err = ErrUserPasswordWrong
		return
	}

	return
}

func FindUserByUserId(user_id string) (user *User, err error) {
	var user_db User
	user_db.UserId = user_id
	db.Where("user_id = ?", user_id).First(&user_db)
	if user_db.Id <= 0 {
		err = fmt.Errorf("user:%s is not found", user_id)
		return
	}
	user = &user_db
	return
}
